let mysql = require('mysql');
let path = require('path');
let fs = require("fs");
let tableName = false;
let folderPath = path.resolve(__dirname, '..') + '/table_column/';

process.argv.forEach(function (val, index, array) {
  let keyVal = val.split('=')
  let key = keyVal[0]
  let value = keyVal[1]
  if (key === 'tableName') {
    tableName = value
  }
});


function toHump(name) { // 蛇型命名改为驼峰命名
  return name.replace(/\_(\w)/g, function(all, letter){
      return letter.toUpperCase();
  });
}

let generatorSettingFile = (tableName, settingPath) =>{
  /**
   * 表名称
   * 示例：var tableName = "admin_visit_reg"
   */
  if (!tableName) {
    console.error('请输入表名称 tableName，例如：npm run table tableName="admin_visit_reg" ')
    return
  }
  var connection = mysql.createConnection({
    host: '172.24.17.200',
    user: 'root',
    password: 'mysql',
    database: 'autumn'
  });
  connection.connect();
  connection.query("select COLUMN_NAME,COLUMN_COMMENT,IS_NULLABLE from information_schema.COLUMNS where table_name = '" + tableName + "' and table_schema = 'autumn';", function(error, results, fields) {
    if (error) throw error;
    let template = ''
    let ruleTeplate = ''
    results.forEach((v) => {
        let field = toHump(v.COLUMN_NAME.toLowerCase())
        let title = v.COLUMN_COMMENT.split('\r\n')[0]
        let type = 'text'
        if (title.indexOf('日期') > -1) {
          type = 'date'
        }
        if (title.indexOf('时间') > -1) {
          type = 'time'
        }

        // 换行模块， 生成setting
        let clo = '{'+ '\n'+'  field: "' + field +'",'+ '\n'+'  title: "'+ title + '"'+ ',\n'+'  type: "'+ type +'"'+'\n'+'}'
        template += clo +','+ '\n'

        // 生成规则
        let ruleItem = '';
        if (v.IS_NULLABLE == 'NO') {
  let ruleItem = `
  ${field}: [
    { required: true, message: '必填项', trigger: 'blur' }
  ],`;
          ruleTeplate += ruleItem
        }
        // console.log(ruleItem)
    });
    let filePath = folderPath + tableName + '.js';
    if (settingPath) {
      filePath = settingPath
    }
    fs.open(filePath , 'w', (err, fd) => {
        if (err) {
            return console.log(err);
        } else {
          console.log(`生成 ${tableName} .js 文件成功 success 100%`)

  let tmp = `
export const setting = [${template}]

export const rule = {${ruleTeplate}}
  `;
            fs.writeFile(fd, tmp , function(err) {
                if (err) {
                  console.log(err)
                }
                console.log('生成表字段设置'+ tableName +'.js设置文件 success 100%');
            });

            // 关闭文件
            fs.close(fd, function(err) {
                if (err) {
                    console.log(err)
                }
            });
        }
    });
  });
  connection.end();
}
if (tableName) {
  generatorSettingFile(tableName);
}

module.exports = generatorSettingFile;
